package com.duoec.doc.mock;

import com.duoec.doc.mock.config.DocMockConfig;
import com.duoec.doc.mock.dto.DuoMockRequest;
import okhttp3.OkHttpClient;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author xuwenzhen
 * @date 2020/2/4
 */
public class DocMockFilter implements Filter {
    private DocMockConfig docMockConfig;
    private OkHttpClient okHttpClient;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        if (!(req instanceof HttpServletRequest)) {
            filterChain.doFilter(req, resp);
            return;
        }
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String mock = request.getHeader("mock");
        if (mock == null && docMockConfig.getMockHeader() != null && docMockConfig.getMockHeader()) {
            //请求头没有设置mock，但服务端强制要求，则不走mock
            filterChain.doFilter(req, resp);
            return;
        }

        DuoMockRequest mockRequest = new DuoMockRequest();

        Enumeration<String> it = request.getHeaderNames();
        while (it.hasMoreElements()) {
            String name = it.nextElement();
            mockRequest.addHeader(name, request.getHeader(name));
        }

        Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

        mockRequest.setParameterMap(request.getParameterMap());
        mockRequest.setUri(request.getRequestURI());

    }

    @Override
    public void destroy() {

    }

    public void setDocMockConfig(DocMockConfig docMockConfig) {
        this.docMockConfig = docMockConfig;
    }

    public void setOkHttpClient(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }
}
